/*
 * @Author: 
 * @Date: 2022-02-15 15:20:20
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-15 15:20:20
 * @Description: 请填写简介
 */
import shortid from 'shortid';
import { utils } from './utils';
import { db } from './database';

export default class Ticket {
  constructor(uniqueId, expiresMinutes = 30) {
    const now = new Date();
    this.unique_id = uniqueId;
    this.token = Ticket.generateToken(uniqueId, now);
    this.crated = now;
    this.expires = moment(now).add(expiresMinutes, 'minute');
  }
  pojo() {
    return {
      ...this
    }
  }
  async save() {
    return await db.from('tickets').insert(this.pojo()).returning('id');
  }
  static async get(uniqueId) {
    const result = await db
      .from('tickets')
      .select('id', 'unique_id', 'token', 'expires', 'created')
      .where('unique_id', unique_id);
    const tickets = JSON.parse(JSON.stringify(result[0]));
    return tickets;
  }
  static generateToken(uniqueId, now) {
    const part1 = uniqueId;
    const part2 = now.getTime().toString();
    const part3 = shortid.generate();
    return utils.sha1(`${part1}:${part2}:${part3}`);
  }
}